package vmi.surgis;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.sql.Time;
import java.util.ArrayList;
import java.util.Calendar;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.graphics.PointF;

public class DataSource implements IDataSource {
	String baseUri = "http://qvit.no-ip.org:8080/SurgisServer/surgis-server";
	
	public DataSource() {
	}
	
	private String buildUriForGetPlacesNamesMethod() {
		return this.baseUri;
	}
	
	private String buildUriForGetPlaceByNameMethod(String name) {
		String res = this.baseUri + "?place=" + name;
		res = res.replaceAll(" ", "%20");
		return res;
	}
	
	private String buildUriForGetPlaceNearestMethod(PointF position, int radius, String category) {
		String res = this.baseUri + "?category=" + category +
					  "&x=" + (int)position.x +
					  "&y=" + (int)position.y +
					  "&radius=" + radius;
		res = res.replaceAll(" ", "%20");
		return res;
	}
	
	private String executeHttpGet(String uri) throws Exception {
    	BufferedReader in = null;
    	try {
    		HttpClient client = new DefaultHttpClient();
    		HttpGet request = new HttpGet();
    		request.setURI(new URI(uri));
    		HttpResponse response = client.execute(request);
    		in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    		StringBuffer sb = new StringBuffer("");
    		String line = "";
    		String NL = System.getProperty("line.separator");
    		while ((line = in.readLine()) != null) {
    			sb.append(line + NL);
    		}
    		in.close();
    		return sb.toString(); 		
    	}
    	finally {
    		if (in != null) {
    			try {
    				in.close();
    			}
    			catch (IOException e) {
    				e.printStackTrace();
    			}
    		}
    	}
    }
	
	private Time time (int h, int m) {
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.HOUR, h);
		calendar.set(Calendar.MINUTE, m);
		calendar.set(Calendar.SECOND, 0);
		return new Time(calendar.getTimeInMillis());
	}
	
	private Time time (String timeString) {
		int hour = Integer.parseInt(timeString.split(":")[0]),
			minute = Integer.parseInt(timeString.split(":")[1]);
		return time(hour, minute);
	}
	
	public String[] getPlacesNames() {
		ArrayList<String> result = new ArrayList<String>();
		String uri = buildUriForGetPlacesNamesMethod();
		String json;
		try {
			json = executeHttpGet(uri);
	        JSONArray jArray = new JSONArray(json);
	        JSONArray places = jArray.getJSONArray(0);
	        for(int i=0; i<places.length(); i++){
	        	result.add(places.getString(i));
	        }
		}
		catch(Exception e){}		
		String[] str_arr = new String[result.size()];
		return result.toArray(str_arr);
	}

	public Place getPlaceByName(String name) {
		String uri = buildUriForGetPlaceByNameMethod(name);
		try {
			String json = executeHttpGet(uri);
			JSONArray jArray = new JSONArray(json);
			JSONObject data = jArray.getJSONObject(0);
			return new Place(name, new PointF(data.getInt("x"), data.getInt("y")), null, null);
		}
		catch (Exception e) {
			return null;
		}
	}

	public Place getPlaceNearest(PointF position, int radius, String category) {
		String uri = buildUriForGetPlaceNearestMethod(position, radius, category);
		try {
			String json = executeHttpGet(uri);
			JSONArray jArray = new JSONArray(json);
			JSONObject data = jArray.getJSONObject(0);
			Time opTime = (category == "cafe") ? time(data.getString("op_time")) : null,
				 clTime = (category == "cafe") ? time(data.getString("cl_time")) : null;
			return new Place(data.getString("place"), new PointF(data.getInt("x"), data.getInt("y")), opTime, clTime);
		}
		catch (Exception e) {
			return null;
		}
	}
}
